package com.atguigu.controller;

import com.atguigu.entity.House;
import com.atguigu.entity.HouseImage;
import com.atguigu.result.Result;
import com.atguigu.service.HouseImageService;
import com.atguigu.util.QiniuUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * @title：
 * @author：Yu
 * @create：2023-02-17 16:21
 * @description：
 */
@Controller
@RequestMapping("/houseImage")
public class HouseImageController {
    @DubboReference
    private HouseImageService houseImageService;

    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String toUpLoadIndex(@PathVariable Long houseId, @PathVariable Integer type, Map map) {
        map.put("houseId", houseId);
        map.put("type", type);
        return "house/upload";
    }

    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result load(@PathVariable Long houseId, @PathVariable Integer type,
                       @RequestParam("file") MultipartFile[] files) throws IOException {

        for (MultipartFile file : files) {
            //  1.将图片上传到七牛云
            String fileName = UUID.randomUUID().toString();
            QiniuUtil.upload2Qiniu(file.getBytes(), fileName);
            //  2.将图片信息存到数据库
            HouseImage houseImage = new HouseImage();
            houseImage.setHouseId(houseId);
            houseImage.setImageName(fileName);
            houseImage.setImageUrl("http://rq6bjm5jq.hn-bkt.clouddn.com/" + fileName);
            houseImage.setType(type);
            houseImageService.insert(houseImage);
        }
        return Result.ok();
    }

    @RequestMapping("/delete/{houseId}/{houseImageId}")
    public String delete(@PathVariable Long houseId, @PathVariable Long houseImageId) {
        //1.从七牛云中删除图片（选做：有的公司不真删，因此只改数据库就可以）
        HouseImage houseImage = houseImageService.findById(houseImageId);
        QiniuUtil.deleteFileFromQiniu(houseImage.getImageName());
        //2.从数据库中删除图片（修改is_deleted）
        houseImageService.delete(houseImageId);
        return "redirect:/house/show/" + houseId;
    }
}
